<template>
  <div class="global-search">
    <el-tooltip content="全局搜索 (Ctrl + K)" placement="bottom">
      <div class="search-trigger" @click="showDialog">
        <el-icon><Search /></el-icon>
        <span class="search-placeholder" v-if="!isCollapse">搜索菜单、功能、数据...</span>
        <span class="shortcut" v-if="!isCollapse">
          <kbd>Ctrl</kbd>
          <kbd>K</kbd>
        </span>
      </div>
    </el-tooltip>

    <el-dialog
      v-model="dialogVisible"
      title="全局搜索"
      width="520px"
      :show-close="false"
      destroy-on-close
      class="search-dialog"
    >
      <div class="search-input">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索控制台..."
          clearable
          @input="handleSearch"
          ref="inputRef"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #suffix>
            <kbd>ESC</kbd>
          </template>
        </el-input>
      </div>

      <div class="search-content" v-loading="loading">
        <template v-if="searchKeyword">
          <template v-if="searchResults.length">
            <div
              v-for="(item, index) in searchResults"
              :key="index"
              class="result-item"
              :class="{ active: currentIndex === index }"
              @click="handleSelect(item)"
              @mouseenter="currentIndex = index"
            >
              <el-icon class="item-icon"><component :is="item.icon" /></el-icon>
              <div class="item-content">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-desc" v-if="item.description">{{ item.description }}</div>
                <div class="item-path" v-if="item.path">{{ item.path }}</div>
              </div>
              <el-tag size="small" :type="item.type">{{ item.category }}</el-tag>
            </div>
          </template>
          <el-empty v-else description="未找到相关内容" />
        </template>
        <template v-else>
          <div v-if="searchHistory.length" class="search-history">
            <div class="history-header">
              <span class="title">搜索历史</span>
              <el-button link type="danger" @click="searchHistory = []">清空</el-button>
            </div>
            <div class="history-list">
              <el-tag
                v-for="(item, index) in searchHistory"
                :key="index"
                class="history-item"
                @click="searchKeyword = item"
              >
                {{ item }}
              </el-tag>
            </div>
          </div>
          
          <div class="search-tips">
            <div class="tip-title">搜索提示</div>
            <div class="tip-list">
              <div class="tip-item">
                <el-icon><Menu /></el-icon>
                <span>搜索菜单: 输入菜单名称</span>
              </div>
              <div class="tip-item">
                <el-icon><Operation /></el-icon>
                <span>快捷功能: 输入功能名称</span>
              </div>
              <div class="tip-item">
                <el-icon><TrendCharts /></el-icon>
                <span>数据统计: 输入指标名称</span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, Menu, Document, Operation, Monitor, TrendCharts, 
  ShoppingCart, Box, Setting, List, Timer, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})

const router = useRouter()
const route = useRoute()
const dialogVisible = ref(false)
const searchKeyword = ref('')
const loading = ref(false)
const currentIndex = ref(0)
const inputRef = ref()
const searchResults = ref([])
const searchHistory = ref<string[]>([])

// 定义搜索结果类型
interface SearchResult {
  title: string
  icon: string
  path?: string
  description?: string
  category: '菜单' | '功能' | '统计' | '系统' | '预警'
  type: '' | 'success' | 'warning' | 'danger' | 'info' | 'primary'
}

// 菜单搜索数据
const menuSearchData: SearchResult[] = [
  {
    title: '控制台',
    icon: 'Monitor',
    path: '/dashboard',
    category: '菜单',
    type: '',
    description: '系统概览与数据统计'
  },
  {
    title: '订单列表',
    icon: 'List',
    path: '/order/list',
    category: '菜单',
    type: '',
    description: '查看和管理所有订单'
  },
  {
    title: '待处理订单',
    icon: 'Timer',
    path: '/order/pending',
    category: '菜单',
    type: '',
    description: '需要立即处理的订单'
  },
  {
    title: '退款管理',
    icon: 'RefreshRight',
    path: '/order/refund',
    category: '菜单',
    type: '',
    description: '处理退款申请'
  },
  {
    title: '商品库存',
    icon: 'Goods',
    path: '/inventory/products',
    category: '菜单',
    type: '',
    description: '商品库存管理'
  },
  {
    title: '入库管理',
    icon: 'TopRight',
    path: '/inventory/in',
    category: '菜单',
    type: '',
    description: '商品入库操作'
  },
  {
    title: '出库管理',
    icon: 'BottomLeft',
    path: '/inventory/out',
    category: '菜单',
    type: '',
    description: '商品出库操作'
  },
  {
    title: '库存预警',
    icon: 'Warning',
    path: '/inventory/warning',
    category: '菜单',
    type: '',
    description: '库存不足预警'
  },
  {
    title: '用户管理',
    icon: 'User',
    path: '/system/users',
    category: '菜单',
    type: '',
    description: '系统用户管理'
  },
  {
    title: '角色管理',
    icon: 'UserFilled',
    path: '/system/roles',
    category: '菜单',
    type: '',
    description: '角色权限配置'
  }
]

// 快捷功能搜索数据
const quickActionData: SearchResult[] = [
  {
    title: '今日销售额',
    icon: 'Money',
    description: '￥12,589',
    category: '统计',
    type: 'success'
  },
  {
    title: '本月订单数',
    icon: 'ShoppingCart',
    description: '1,234',
    category: '统计',
    type: 'primary'
  },
  {
    title: '库存预警',
    icon: 'Warning',
    description: '5个商品库存不足',
    category: '预警',
    type: 'warning'
  },
  {
    title: '系统状态',
    icon: 'Monitor',
    description: '运行正常',
    category: '系统',
    type: 'info'
  },
  {
    title: '创建订单',
    icon: 'Plus',
    path: '/order/create',
    category: '功能',
    type: 'primary',
    description: '快速创建新订单'
  },
  {
    title: '商品上架',
    icon: 'Upload',
    path: '/product/create',
    category: '功能',
    type: 'primary',
    description: '添加新商品'
  }
]

const handleSearch = async () => {
  if (!searchKeyword.value) {
    searchResults.value = []
    return
  }
  
  loading.value = true
  await new Promise(resolve => setTimeout(resolve, 300))
  
  const keyword = searchKeyword.value.toLowerCase()
  
  // 搜索菜单和功能
  searchResults.value = [
    ...menuSearchData.filter(item => 
      item.title.toLowerCase().includes(keyword) ||
      item.description?.toLowerCase().includes(keyword)
    ),
    ...quickActionData.filter(item =>
      item.title.toLowerCase().includes(keyword) ||
      item.description?.toLowerCase().includes(keyword)
    )
  ]
  
  loading.value = false
  currentIndex.value = 0
}

const handleSelect = (item: SearchResult) => {
  if (item.path) {
    router.push(item.path)
    ElMessage.success(`正在跳转到${item.title}`)
  } else {
    ElMessage.success(`查看${item.title}详情`)
  }
  dialogVisible.value = false
  searchKeyword.value = ''
}

const showDialog = () => {
  dialogVisible.value = true
  setTimeout(() => {
    inputRef.value?.focus()
  }, 100)
}

// 键盘快捷键
const handleKeydown = (e: KeyboardEvent) => {
  // Ctrl + K 打开搜索
  if (e.ctrlKey && e.key === 'k') {
    e.preventDefault()
    showDialog()
  }
  
  if (!dialogVisible.value) return
  
  // ESC 关闭
  if (e.key === 'Escape') {
    dialogVisible.value = false
    return
  }
  
  // 上下键选择
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    currentIndex.value = (currentIndex.value + 1) % searchResults.value.length
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    currentIndex.value = currentIndex.value - 1 < 0 
      ? searchResults.value.length - 1 
      : currentIndex.value - 1
  }
  
  // 回车确认
  if (e.key === 'Enter' && searchResults.value.length) {
    handleSelect(searchResults.value[currentIndex.value])
  }
}

// 记录搜索历史
const addToHistory = (keyword: string) => {
  if (!keyword) return
  const index = searchHistory.value.indexOf(keyword)
  if (index > -1) {
    searchHistory.value.splice(index, 1)
  }
  searchHistory.value.unshift(keyword)
  if (searchHistory.value.length > 10) {
    searchHistory.value.pop()
  }
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 初始化时加载搜索历史
onMounted(() => {
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
  window.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.global-search {
  .search-trigger {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background-color: var(--el-bg-color-page);
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    
    .search-placeholder {
      color: var(--el-text-color-secondary);
      font-size: 13px;
      white-space: nowrap;
    }
    
    .shortcut {
      margin-left: auto;
      display: flex;
      gap: 4px;
      
      kbd {
        padding: 2px 4px;
        font-size: 12px;
        background: #eee;
        border-radius: 3px;
        border: 1px solid #ccc;
      }
    }
    
    &:hover {
      background-color: var(--el-bg-color);
    }
  }
}

.search-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 12px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
  
  .search-input {
    padding: 12px 0;
    
    :deep(.el-input__wrapper) {
      padding-right: 8px;
    }
    
    kbd {
      padding: 2px 4px;
      font-size: 12px;
      background: #eee;
      border-radius: 3px;
      border: 1px solid #ccc;
    }
  }
  
  .search-content {
    max-height: 400px;
    overflow-y: auto;
    
    .result-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      cursor: pointer;
      border-radius: 6px;
      
      .item-icon {
        font-size: 20px;
        color: var(--el-text-color-secondary);
      }
      
      .item-content {
        flex: 1;
        
        .item-title {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .item-desc {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
        
        .item-path {
          font-size: 12px;
          color: var(--el-text-color-secondary);
          margin-top: 4px;
        }
      }
      
      &.active,
      &:hover {
        background-color: var(--el-color-primary-light-9);
      }
    }
    
    .search-tips {
      padding: 12px;
      
      .tip-title {
        font-size: 13px;
        color: var(--el-text-color-secondary);
        margin-bottom: 12px;
      }
      
      .tip-list {
        .tip-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 0;
          color: var(--el-text-color-regular);
          font-size: 13px;
        }
      }
    }
  }
}

.search-history {
  padding: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .title {
      font-size: 13px;
      color: var(--el-text-color-secondary);
    }
  }
  
  .history-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .history-item {
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}
</style> 